<?php
require_once (dirname(__FILE__) .'/Session.php');
require_once (dirname(__FILE__) .'/db/DbTables/PtProject.php');
require_once (dirname(__FILE__) .'/db/DbTables/PtCMS.php');
require_once (dirname(__FILE__) .'/db/DbTables/PtDefaultStyle.php');
require_once (dirname(__FILE__) .'/db/DbTables/PtPreConfiguredDesign.php');
require_once (dirname(__FILE__) .'/db/DbTables/PtConfiguredDesign.php');

class PrestathemeEditor
{
	protected $_project;
	protected $_cms;
	protected $_editor;
	
	public $styles;
	public $design;
	
    public function __construct ($id_project, $id_owner, $token, $lang_iso)
    {
        Session::getInstance()->id_project = $id_project;
        Session::getInstance()->id_owner   = $id_owner;
        Session::getInstance()->token      = $token;
        Session::getInstance()->lang       = $lang_iso;
    }
	
	public function init ()
	{
		$this->_project = new PtProject(Session::getInstance()->id_project);
		$this->_cms     = new PtCMS($this->_project->id_cms, _PT_DEFAULT_LANG_ISO_);
		
		// Init editor configs
		$this->_initEditor();
        
        // Init configurations
		$this->_loadConfigStyle();
		
		$json = array();
		//	Get current style throught a JSON data
		$json['styles'] = $this->_initJSONConfigs();
		
		// Load configurations
		$json['design'] = $this->_loadConfigDesign();
		
		//	Return the current css style
		return $json;
	}
    
    private function _initEditor ()
    {
        $this->_editor = array();
        
        // Load tabs
        $this->_editor['tabs'] = DbAbstract::getInstance()->executeS('
            SELECT e.`id_editor`, tab.`id_tab`, tab.`name`, tabl.`label`, tabl.`description`
            FROM `'. _PT_DB_PREFIX_ .'theme_editor` e
            LEFT JOIN `'. _PT_DB_PREFIX_ .'config_tab` tab ON (tab.`id_editor` = e.`id_editor` AND tab.`active` = 1)
            LEFT JOIN `'. _PT_DB_PREFIX_ .'config_tab_lang` tabl ON (tab.`id_tab` = tabl.`id_tab` AND tabl.`lang_iso` = \''. Session::getInstance()->lang .'\')
            WHERE e.`id_cms` = '. (int)$this->_project->id_cms .' AND e.`active` = 1
            ORDER BY tab.`position` ASC
        ');
        
        // For each tabs, load items tree
        foreach ($this->_editor['tabs'] AS &$tab) {
            // Item recursively
            $tab['items'] = $this->_recursiveGetSubItems('item.`id_tab` = '. (int)$tab['id_tab']);
        }
        /*
        echo '<pre>';
        print_r($this->_editor);
        echo '</pre>';die();*/
    }
    
    private function _recursiveGetSubItems ($filter) 
    {
        $items = DbAbstract::getInstance()->executeS('
            SELECT item.`id_item`, item.`name`, iteml.`label`, iteml.`description`
            FROM `'. _PT_DB_PREFIX_ .'config_item` item
            LEFT JOIN `'. _PT_DB_PREFIX_ .'config_item_lang` iteml ON (item.`id_item` = iteml.`id_item` AND iteml.`lang_iso` = \''. Session::getInstance()->lang .'\')
            WHERE '. $filter .' AND item.`active` = 1
            ORDER BY item.`position` ASC
        ');
        foreach ($items AS &$item) {
            if ($subItems = $this->_recursiveGetSubItems(' item.`id_parent` = '. (int)$item['id_item'])) {
                $item['subitems'] = $subItems;
            }
            
            // For each items, load options
            $item['options'] = DbAbstract::getInstance()->executeS('
                SELECT opt.`id_option`, opt.`id_style`, opt.`name`, opt.`namespace`, opt.`type`, optl.`label`, optl.`description`
                FROM `'. _PT_DB_PREFIX_ .'config_option` opt
                LEFT JOIN `'. _PT_DB_PREFIX_ .'config_option_lang` optl ON (opt.`id_option` = optl.`id_option` AND optl.`lang_iso` = \''. Session::getInstance()->lang .'\')
                WHERE opt.`id_item` = '. (int)$item['id_item'] .' AND opt.`active` = 1
                ORDER BY opt.`position` ASC
            ');
            // For each items, load style: default and updates
            foreach ($item['options'] AS &$option) {
                $option['default_style'] = DbAbstract::getInstance()->getRow('
                    SELECT style.`selector`, style.`style`
                    FROM `'. _PT_DB_PREFIX_ .'default_style` style
                    WHERE style.`id_style` = '. (int)$option['id_style'] .' AND style.`active` = 1
                ');
                $option['custom_style'] = DbAbstract::getInstance()->getRow('
                    SELECT style.`selector`, style.`style`
                    FROM `'. _PT_DB_PREFIX_ .'custom_style` style
                    WHERE style.`id_style` = '. (int)$option['id_style'] .' AND style.`id_project` = '. (int)$this->_project->id .'
                ');
            }
        }
        return $items;
    }
	
	public function getUrl ()
	{
		return $this->_cms->url;
	}
    
    public function displayTabs () 
    {
        $output = '';
        foreach ($this->_editor['tabs'] AS $tab) {
            $output .= '<li id="'. $tab['name'] .'" title="'. $tab['label'] .'"> &nbsp; </li>';
        }
        return $output;
    }
    
    public function displayEditorTools ()
    {
        $output = '';
        foreach ($this->_editor['tabs'] AS $tab) {
            $output .= '
            <div id="block-'. $tab['name'] .'" class="switchboard">
                <div class="header">'. $tab['label'] .'</div>
                <div class="config-content">';
            foreach ($tab['items'] AS $item) {
                $output .= '
                <div class="config_tool" id="item-'. $item['id_item'] .'">
                    <h3>
                        '. $item['label'] .'<br />
                        <span class="item_description">'. $item['description'] .'</span>
                    </h3>
                    <div class="block-content">
                        <div class="va-content">'. $this->displayItemRecursively($item) .'</div>
                    </div>
                </div>';
            }
            $output .= '
                </div>
            </div>';
        }
        return $output;
    }
    
    private function displayItemRecursively ($item)
    {
        $fontsFamily = array(
            'Arial' => 'Arial',
            'Times New Roman' => 'Times New Roman',
        );
        
        $output = '';
        if (isset($item['subitems'])) {
            foreach ($item['subitems'] AS $subitem) {
                $output .= '
                <div class="sub-config_tool" id="item-'. $subitem['id_item'] .'">
                    <h4>
                        '. $subitem['label'] .'<br />
                        <span class="item_description">'. $subitem['description'] .'</span>
                    </h4>
                    <div class="sub-block-content">
                        <div class="sub-va-content">'. $this->displayItemRecursively($subitem) .'</div>
                    </div>
                </div>
                ';
            }
        }
        $value = 'columns_3_LCR';
        if (isset($item['options'])) {
            foreach ($item['options'] AS $option) {
                if ($option['type'] == 'DES-Columns') {
                    $output .= '
                    <div class="va-content">
            			<div class="design_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
                        '. $this->_displayDesignSelect('', '', '', '', '', '', $this->_getDesignOptions('designsColumn', $option)) .'<br />
                    </div>';
                // } elseif ($option['type'] == 'DES-Column') {
                } elseif ($option['type'] == 'DES-SelectedDesign') {
                } elseif ($option['type'] == 'DES-ActiveShadow') {
                } elseif ($option['type'] == 'DES-Shadow') {
                } elseif ($option['type'] == 'DES-ActiveRadius') {
                } elseif ($option['type'] == 'DES-Radius') {
                } elseif ($option['type'] == 'DES-ListDesign') {
                } elseif ($option['type'] == 'CSS-Block') {
                } elseif ($option['type'] == 'DES-Dim') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="dim_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>'. $this->_displayDimInput('', '', '', '', '', 'px') .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-TopRightBottomLeft') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="dim_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
            			'. $this->_displayDimInput('', '', '', 'left', '', 'px') .'
            			'. $this->_displayDimInput('', '', '', 'top', '', 'px') .'
            			'. $this->_displayDimInput('', '', '', 'bottom', '', 'px') .'
            			'. $this->_displayDimInput('', '', '', 'right', '', 'px') .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-BoxDim') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="dim_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
            			'. $this->_displayDimInput('', '', '', 'width', '', 'px') .'
                        <span class="width_height">x</span>
            			'. $this->_displayDimInput('', '', '', 'height', '', 'px') .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-Color') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="color_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
            			'. $this->_displayColorPicker('', '', '', '', '', '') .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-Text') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="color_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
            			'. $this->_displayFamilyInput('', '', '', '', 'Font name', $fontsFamily) .'
            			'. $this->_displayDimInput('', '', '', '', 'Font size', 'px') .'
            			'. $this->_displayColorPicker('', '', '', '', 'Font color', '') .'
                        '. $this->_displayDesignSelect('', '', '', '', 'Font align', '', $this->_getDesignOptions('designsTextAlign', $option)) .'
                        '. $this->_displayDesignSelect('', '', '', '', 'Font transform', '', $this->_getDesignOptions('designsTextTransform', $option)) .'
                        '. $this->_displayDesignMultiSelect('', '', '', '', 'Font design', '', $this->_getDesignOptions('designsTextDesign', $option)) .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-Link') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="color_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
            			'. $this->_displayFamilyInput('', '', '', '', 'Font name', $fontsFamily) .'
            			'. $this->_displayDimInput('', '', '', '', 'Font size', 'px') .'
            			'. $this->_displayColorPicker('', '', '', '', 'Font color', '') .'
                        '. $this->_displayDesignSelect('', '', '', '', 'Font align', '', $this->_getDesignOptions('designsTextAlign', $option)) .'
                        '. $this->_displayDesignSelect('', '', '', '', 'Font transform', '', $this->_getDesignOptions('designsTextTransform', $option)) .'
                        '. $this->_displayDesignMultiSelect('', '', '', '', 'Font design', '', $this->_getDesignOptions('designsTextDesign', $option)) .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-Border') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="imag_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
                        '. $this->_displayDesignMultiSelect('', '', '', '', 'Active border', '', $this->_getDesignOptions('designsBorder', $option)) .'
            			'. $this->_displayDimInput('', '', '', '', 'Border size', 'px') .'
            			'. $this->_displayColorPicker('', '', '', '', 'Border color', '') .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-Image') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="imag_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
                        '. $this->_displayDesignMultiSelect('', '', '', '', 'Active border', '', $this->_getDesignOptions('designsBorder', $option)) .'
            			'. $this->_displayDimInput('', '', '', '', 'Border size', 'px') .'
            			'. $this->_displayColorPicker('', '', '', '', 'Border color', '') .'
            			<div class="clear"></div>
                    </div>
                    ';
                } elseif ($option['type'] == 'CSS-Background') {
                } elseif ($option['type'] == 'CSS-Other') {
                    $output .= '
                    <div class="cssdesign">
            			<div class="color_label">
            				<label for="styles-'. str_replace('/', '-', $option['namespace']) .'">'. $option['label'] .'</label> : 
            			</div>
            			<div class="color_picker_value">
            				<input type="text" class="cssvalue select_'. $option['type'] .'" readonly="readonly" id="value_styles-'. str_replace('/', '-', $option['namespace']) .'" name="styles['. str_replace('/', '][', $option['namespace']) .'][value]" value="'. (isset($option['custom_style']['style']) ? $option['custom_style']['style'] : $option['default_style']['style']) .'" size="7" />
            				<div id="styles-'. str_replace('/', '-', $option['namespace']) .'" class="select'. ucfirst($option['type']) .'"><div style="'. (isset($option['custom_style']['style']) ? $option['custom_style']['style'] : $option['default_style']['style']). '"></div></div>
            			</div>
            			<div class="clear"></div>
            		
            			<input type="hidden" id="selector_styles-'. str_replace('/', '-', $option['namespace']) .'"  class="cssselector"  value="'. (isset($option['custom_style']['style']) ? $option['custom_style']['selector'] : $option['default_style']['selector']) .'" />
            			<input type="hidden" id="fullvalue_styles-'. str_replace('/', '-', $option['namespace']) .'" class="cssfullvalue" value="'. (isset($option['custom_style']['style']) ? $option['custom_style']['style'] : $option['default_style']['style']) .'" />
            			<input type="hidden" id="attr_styles-'. str_replace('/', '-', $option['namespace']) .'"      class="cssattr"      value="'. (isset($option['custom_style']['style']) ? $option['custom_style']['style'] : $option['default_style']['style']) .'" />
                    </div>
                    ';
                }
            }
        }
        return $output;
    }
    
    private function _displayDesignSelect ($value='', $id='', $name='', $class='', $label='', $selector='', $designs=array()) {
        $output = '
            <div class="selection">
			'. (empty($label)?'':('<label for="'. $id .'">'. $label .'</label>')) .'
                <div class="select-design layout">';
        foreach ($designs AS $k=>$v) {
            $output .= '
                    <div class="design-option'. ($value == $k ? ' active' : '') . $k .'" id="'. $v['namespace'] .'">
                        <img src="media/img/'. $k .'.png" height="'. $v['height'] .'" width="'. $v['width'] .'" alt="01" title="'. $v['label'] .'" />
                        <input type="radio" class="hide choose_design" name="'. $v['namespace'] .'" id="'. $v['namespace'] .'" value="'. $k .'" '. ($value == $k ? 'checked="checked"' : '') .' />
                    </div>';
        }
        $output .= '
                    <div class="clear"></div>
                </div>
                <div class="hide">
            		<input type="hidden" id="'. $id .'"  class="cssselector"  value="'. $selector .'" />
                </div>
        	</div>
        ';
        return $output;
    }
    private function _displayDesignMultiSelect ($value='', $id='', $name='', $class='', $label='', $selector='', $designs=array()) {
        $output = '
            <div class="selection">
			'. (empty($label)?'':('<label for="'. $id .'">'. $label .'</label>')) .'
                <div class="multiselect-design layout">';
        foreach ($designs AS $k=>$v) {
            $output .= '
                    <div class="design-option multiselect'. ($value == $k ? ' active' : '') . $k .'" id="'. $v['namespace'] .'">
                        <img src="media/img/'. $k .'.png" height="'. $v['height'] .'" width="'. $v['width'] .'" alt="01" title="'. $v['label'] .'" />
                        <input type="checkbox" class="hide choose_design" name="'. $v['namespace'] .'" id="'. $v['namespace'] .'" value="'. $k .'" '. ($value == $k ? 'checked="checked"' : '') .' />
                    </div>';
        }
        $output .= '
                    <div class="clear"></div>
                </div>
                <div class="hide">
            		<input type="hidden" id="'. $id .'"  class="cssselector"  value="'. $selector .'" />
                </div>
        	</div>
        ';
        return $output;
    }
    private function _displayDimInput ($value='', $id='', $name='', $class='', $label='', $unit='px') {
        return '
		<div class="dim_value '. $class .'">
			'. (empty($label)?'':('<label for="'. $id .'">'. $label .'</label>')) .'
			<input type="text" class="cssdim" id="'. $id .'" name="'. $name .'" value="'. $value .'" size="2" />
            <select name="unit-'. $name .'">
                <option value="px"'. ($unit=='px'?' selected="selected"':'') .'>px</option>
                <option value="%"' . ($unit=='%'?' selected="selected"':'')  .'>%</option>
                <option value="em"'. ($unit=='em'?' selected="selected"':'') .'>em</option>
            </select>
		</div>';
    }
    private function _displayColorPicker ($value='', $id='', $name='', $class='', $label='Color', $namespace='') {
        return '
		<div class="color_picker_value '. $class .'">
			'. (empty($label)?'':('<label for="'. $id .'">'. $label .'</label>')) .'
			<input type="text" class="cssvalue select_color" readonly="readonly" id="'. $id .'" name="'. $name .'" value="'. $value .'" size="7" />
			<div id="styles-'. $namespace .'" class="selectColor"><div style=""></div></div>
		</div>';
    }
    private function _displayFamilyInput ($value='', $id='', $name='', $class='', $label='Family', $availableFamily = array()) {
        $output = '
		<div class="family_value '. $class .'">
			'. (empty($label)?'':('<label for="'. $id .'">'. $label .'</label>')) .'
            <select name="'. $name .'" id="'. $id .'">';
        foreach ($availableFamily AS $k=>$v) {
            $output .= '<option value="'.$k.'" style="family:\''. $k .'\'"'. ($value==$k?' selected="selected"':'') .'>'. $v .'</option>';
        }
        $output .= '
            </select>
		</div>';
        return $output;
    }
    
    private function _getDesignOptions ($type, $option) {
        if ($type == 'designsTextAlign') {
            return array(
                'alignLeft'=>array(
                    'namespace' => $option['namespace'].'-alignLeft',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Left',
                ),
                'alignCenter'=>array(
                    'namespace' => $option['namespace'].'-alignCenter',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Center',
                ),
                'alignRight'=>array(
                    'namespace' => $option['namespace'].'-alignRight',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Right',
                ),
                'alignJustify'=>array(
                    'namespace' => $option['namespace'].'-alignJustify',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Justify',
                ),
            );
        } elseif ($type == 'designsTextTransform') {
            return array(
                'upper'=>array(
                    'namespace' => $option['namespace'].'-upper',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Upper case',
                ),
                'lower'=>array(
                    'namespace' => $option['namespace'].'-lower',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Lower case',
                ),
                'capitalize'=>array(
                    'namespace' => $option['namespace'].'-capitalize',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Capitalize',
                ),
            );
        } elseif ($type == 'designsTextDesign') {
            return array(
                'bold'=>array(
                    'namespace' => $option['namespace'].'-bold',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Bold',
                ),
                'italic'=>array(
                    'namespace' => $option['namespace'].'-italic',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Italic',
                ),
                'underline'=>array(
                    'namespace' => $option['namespace'].'-underline',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Underline',
                ),
            );
        } elseif ($type == 'designsBorder') {
            return array(
                'top'=>array(
                    'namespace' => $option['namespace'].'-top',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Bold',
                ),
                'left'=>array(
                    'namespace' => $option['namespace'].'-left',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Italic',
                ),
                'bottom'=>array(
                    'namespace' => $option['namespace'].'-bottom',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Underline',
                ),
                'right'=>array(
                    'namespace' => $option['namespace'].'-right',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Underline',
                ),
            );
        } elseif ($type == 'designsColumn') {
            return array(
                'column_1_C'=>array(
                    'namespace' => $option['namespace'].'-column_1_C',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'One column',
                ),
                'columns_2_CR'=>array(
                    'namespace' => $option['namespace'].'-columns_2_CR',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Two columns (Center - right)',
                ),
                'columns_2_LC'=>array(
                    'namespace' => $option['namespace'].'-columns_2_LC',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Two columns (Left - Center)',
                ),
                'columns_3_CLR'=>array(
                    'namespace' => $option['namespace'].'-columns_3_CLR',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Tree columns (Center - Left - Right)',
                ),
                'columns_3_LCR'=>array(
                    'namespace' => $option['namespace'].'-columns_3_LCR',
                    'height'    => '62',
                    'width'     => '82',
                    'label'     => 'Tree columns (Left - Center - Right)',
                ),
            );
        }
    }
	
	public function saveStyle ($styles)
	{
		$ok = true;
		foreach ($styles AS $selector => $styles)
		{
			$style = PtDefaultStyle::getByIdProjectAndSelector ($this->_project->id, $selector);
			$style->style = '';
			foreach ($styles As $attr => $val)
			{
				$style->style .= $attr .':'. $val .';';
			}
			$ok &= $style->save();
		}
		
		return $ok;
	}
	
	public function saveDesign ($design)
	{
		$ok = true;
		foreach ($design AS $namespace => $key_name)
		{
			$namespace = explode('-', $namespace);
			array_shift($namespace);
			$namespace = implode('/', $namespace);
			
			$designConfig = PtConfiguredDesign::getByIdProjectAndNamespace ($this->_project->id, $namespace);
			$designConfig->key_name   = $key_name;
			
			$ok &= $designConfig->save();
		}
		
		return $ok;
	}
	
	protected function _loadConfigStyle ()
	{
		$this->styles = new stdClass();
		
		//	1.	Main Layout
		$this->styles->mainlayout = new stdClass();
		
		//	1.1.	background-color
		$this->_setConfigStyle ('mainlayout/bgcolor', 'html body', 'background-color', 'background');
		
		//	1.2.	page background-color
		$this->_setConfigStyle ('mainlayout/page_bgcolor', 'html body div#page', 'background-color', 'background');
		
		// 2. Header
			// 2.1. Main Menu
				// 2.1.3. background color
		$this->_setConfigStyle ('header/mainmenu/bgcolor', 'html .sf-menu', 'background-color', 'background');
		$this->_setConfigStyle ('header/mainmenu/a_bgcolor', 'html .sf-menu a', 'background-color', 'background');
				// 2.1.4. linebetween color
		$this->_setConfigStyle ('header/mainmenu/linebetween', 'html .sf-menu li', 'background-color', 'background');
				// 2.1.5. text color
		$this->_setConfigStyle ('header/mainmenu/color', 'html .sf-menu a', 'color', 'color');
				// 2.1.6. hover|actvie|focus
		$this->_setConfigStyle ('header/mainmenu/actvie', 'html .sf-menu a:focus, html .sf-menu a:hover, html .sf-menu a:active', 'background-color', 'background');
				// 2.1.7. submenu background
		$this->_setConfigStyle ('header/mainmenu/submenu_bgcolor', 'html .sf-menu li li, html .sf-menu li li li', 'background-color', 'background');
				// 2.1.8. submenu hover
		$this->_setConfigStyle ('header/mainmenu/submenu_hover', 'html .sf-menu ul li:hover, html .sf-menu ul li.sfHover, html .sf-menu ul li.sfHoverForce, html .sf-menu ul li a:focus, html .sf-menu ul li a:hover, html .sf-menu ul li a:active', 'background-color', 'background');
			// 2.2. Search
				// 2.2.1. Input text Background color
		$this->_setConfigStyle ('header/search/bgcolor', 'html #search_block_top #search_query_top', 'background-color', 'background');
				// 2.2.2. Input text Border color
		$this->_setConfigStyle ('header/search/bdcolor', 'html #search_block_top #search_query_top', 'border-color', 'border');
				// 2.2.3. Button background color
		$this->_setConfigStyle ('header/search/button_bgcolor', 'html #search_block_top .button', 'background-color', 'background');
				// 2.2.4. Button text color
		$this->_setConfigStyle ('header/search/button_color', 'html #search_block_top .button', 'color', 'color');
			// 2.3. Cart
				// 2.3.1. background color
		$this->_setConfigStyle ('header/cart/bgcolor', 'html #header #shopping_cart a', 'background-color', 'background');
		$this->_setConfigStyle ('header/cart/cart_bgcolor', 'html #header #cart_block', 'background-color', 'background');
				// 2.3.2. text color
		$this->_setConfigStyle ('header/cart/color', 'html #header #shopping_cart, html #shopping_cart a, html #shopping_cart a:active, html #shopping_cart a:visited', 'color', 'color');
		$this->_setConfigStyle ('header/cart/cart_color', 'html #cart_block', 'color', 'color');
		$this->_setConfigStyle ('header/cart/cart_link_color', 'html #cart_block #cart_block_list a, html #cart_block #cart_block_list a:active, html #cart_block #cart_block_list a:visited', 'color', 'color');
			// 2.4. Header
				// 2.4.1. background color
		$this->_setConfigStyle ('header/header/bgcolor', 'html #header', 'background-color', 'background');
				// 2.4.2. text color
		$this->_setConfigStyle ('header/header/color', 'html ul#header_links li, html ul#header_links li a, html #header_user_info, html #header_user_info a', 'color', 'color');
		// 5. Columns
			// 5.1. Background color
		$this->_setConfigStyle ('columns/bgcolor', 'html #columns .column', 'background-color', 'background');
			// 5.2. Read more link
		$this->_setConfigStyle ('columns/readmore_color', 'html #columns .column a.lnk_more', 'color', 'color');
			// 5.3. li separator
		$this->_setConfigStyle ('columns/separator', 'html #columns .column #categories_block_left li, html #columns .column .blockmanufacturer li, html #columns .column .informations_block_left li, html #columns .column #new-products_block_right dd, html #columns .column .inline_list li', 'border-bottom-color', 'border-bottom');
			// 5.4. Price text color
		$this->_setConfigStyle ('columns/price_color', 'html #columns .column .price', 'color', 'color');
		// 6. Blocks
			// 6.1. Block Header
				// 6.1.1. background color
		$this->_setConfigStyle ('block/header/bgcolor', 'html #columns .column .block h4', 'background-color', 'background');
				// 6.1.2. text color
		$this->_setConfigStyle ('block/header/color', 'html #columns .column .block h4, html #columns .column .block h4 a', 'color', 'color');
			// 6.2. Block Content
				// 6.2.1. background color
		$this->_setConfigStyle ('block/content/bgcolor', 'html #columns .column .block', 'background-color', 'background');
		// 7. Footer
			// 7.1. background color
				// 7.1.2.	page background-color
		$this->_setConfigStyle ('footer/bgcolor', 'html #footer #reinsurance_block', 'background-color', 'background');
	}
	
	protected function _setConfigStyle ($namespaces, $selector, $attr, $attrForFullValue)
	{
		// get fields from namespace
		$namespaces = explode('/', $namespaces);
		$styles = &$this->styles;
		
		foreach ($namespaces AS $namespace)
		{
			if (is_object($styles) AND !property_exists($styles, $namespace))
			{
				$styles->{$namespace} = new stdClass();
			}
			$styles = &$styles->{$namespace};
		}
		
		// set default fields
		$styles->selector  = $selector;
		$styles->attr      = $attr;
		$styles->value     = $this->_project->getCssStyle($selector, $attr);
		$styles->fullvalue = $this->_formatStyle($this->_project->getCssStyle($selector/* , $attrForFullValue */));
	}
	
	public function displayStyleConfig ($label, $namespace, $type = 'color', $attr = 'background-color')
	{
		// Select the current namespace
		$namespaces = explode('/', $namespace);
		$styles = &$this->styles;
		
		foreach ($namespaces AS $namespace)
		{
			if (is_object($styles) AND !property_exists($styles, $namespace))
			{
				$styles->{$namespace} = new stdClass();
			}
			$styles = &$styles->{$namespace};
		}
		
		return '
			<div class="color_label">
				<label for="styles-'. implode('-', $namespaces) .'">'. $label .'</label> : 
			</div>
			<div class="color_picker_value">
				<input type="text" class="cssvalue select_'. $type .'" readonly="readonly" id="value_styles-'. implode('-', $namespaces) .'" name="styles['. implode('][', $namespaces) .'][value]" value="'. $styles->value .'" size="7" />
				<div id="styles-'. implode('-', $namespaces) .'" class="select'. ucfirst($type) .'"><div style="'. $attr .':'. $styles->value. '"></div></div>
			</div>
			<div class="clear"></div>
		
			<input type="hidden" id="selector_styles-'. implode('-', $namespaces) .'"  class="cssselector"  value="'. $styles->selector .'" />
			<input type="hidden" id="fullvalue_styles-'. implode('-', $namespaces) .'" class="cssfullvalue" value="'. $styles->fullvalue .'" />
			<input type="hidden" id="attr_styles-'. implode('-', $namespaces) .'"      class="cssattr"      value="'. $styles->attr .'" />
		';
	}
	
	protected function _loadConfigDesign ()
	{
		$preConfig = PtPreConfiguredDesign::getByIdCms($this->_cms->id, true);
		
		$jsonArray      = array();
		foreach ($preConfig AS $designPreConfig)
		{
			$namespaces = explode('/', $designPreConfig->namespace);
			$design = &$this->design;
			
			foreach ($namespaces AS $namespace)
			{
				if (is_object($design) AND !property_exists($design, $namespace))
				{
					$design->{$namespace} = new stdClass();
				}
				$design = &$design->{$namespace};
			}
			
			$designConfig = PtConfiguredDesign::getByIdProjectAndNamespace($this->_project->id, $designPreConfig->namespace);
			
			$design->type = empty($designConfig->id) ? $designPreConfig->key_name : $designConfig->key_name;
			
			$jsonArray[] = array(
				'classChoosen' => $design->type, 
				'elemName' => 'design-'. str_replace('/', '-', $designPreConfig->namespace), 
				'targetElem' => $designPreConfig->target_element
			);
		}
		
		return json_encode($jsonArray);
	}
	
	protected function _initJSONConfigs ()
	{
		$jsonArray = array();
		$jsonArray = $this->_getConfig($this->styles, $jsonArray);
		return json_encode($jsonArray);
	}
	
	protected function _formatStyle ($styleArray)
	{
		if (is_array($styleArray))
		{
			$fullvalue = '';
			foreach ($styleArray AS $attr => $value)
				$fullvalue .= trim($attr) .':'. trim($value) .';';
				
			$styleArray = trim($fullvalue, ';');
		}
		
		return $styleArray;
	}
	
	protected function _getConfig ($styles, &$jsonArray = array())
	{
		if (is_object($styles) AND (get_class($styles) == 'stdClass'))
		{
			$stylesArray = (array)$styles;
			if (isset($stylesArray['selector']) AND is_string($stylesArray['selector']))
			{
				$jsonArray[] = $stylesArray;
			}
			else
			{
				foreach ($stylesArray AS $config => $styles)
				{
					if (is_object($styles) AND (get_class($styles) == 'stdClass'))
					{
						$this->_getConfig($styles, $jsonArray);
					}
				}
			}
		}
		
		return $jsonArray;
	}
}